package io;
/**
 * FileControler
 * 
 * Implements a controler that permits to copy or manage files by URL easily
 * 
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Scanner;

public class FileControler {

	//File copy
	public static void copy(String in, String out){
		try{
			int bytes_read=0;
			byte [] buffer=  new byte[512];
			FileInputStream fin = new FileInputStream(in);
			FileOutputStream fout = new FileOutputStream(out);
			while ((bytes_read =fin.read(buffer)) != -1) {
				fout.write(buffer,0,bytes_read);
			}
			fin.close();
			fout.close();
		}
		catch(IOException ioe){
			ioe.printStackTrace();
		}
	}

	public static void copyURLFile(String in, String out) {
		try
		{
			URL url  = new URL(in);
			System.out.println("Opening connection to " + url);
			URLConnection urlC = url.openConnection();
			// Copy resource to local file, use remote file
			// if no local file name specified
			InputStream is = url.openStream();
			// Print info about resource
			System.out.print("Copying resource (type: " +
					urlC.getContentType());
			Date date=new Date(urlC.getLastModified());
			System.out.println(", modified on: " +
					date.toLocaleString() + ")...");
			System.out.flush();
			FileOutputStream fout = new FileOutputStream(out);
			int oneChar, count=0;
			while ((oneChar=is.read()) != -1)
			{
				fout.write(oneChar);
				count++;
			}
			is.close();
			fout.close();
			System.out.println(count + " byte(s) copied");
		}
		catch (MalformedURLException e) {
			System.err.println(e.toString());
		}
		catch (IOException e) {
			System.err.println(e.toString());
		}
	}
	
	//Return contents of a dtd file
	public static String getFileContents(String filePath){
		String res = "";
		
		Scanner scanner;
		try {
			scanner = new Scanner(new File(filePath));
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
			    //System.out.println(line);
				res += line+"\n";
			}
			scanner.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
}	


